/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license.txt -file, included in
 * the distribution.
 */

#include "myqmlapplicationviewer.h"

#include <QDebug>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <QGraphicsObject>
#include <QTimer>

#ifdef Q_OS_SYMBIAN
    #include <aknedsts.h>
    #include <coeaui.h>
    #include <coemain.h>
    #include <w32std.h>
    #define EAknEditorFlagEnablePartialScreen 0x200000
#endif

#include "audioplayer.h"
#include "screensizeprovider.h"

#ifdef INAPP_BILLING
#include "productcatalogmodel.h"
#include "declarativepurchaselistmodel.h"
#include "itemstatusimageprovider.h"
#include "resourcedataprovider.h"
#include <QSortFilterProxyModel>
#endif //INAPP_BILLING

/*!
  Constructor.
*/
MyQmlApplicationViewer::MyQmlApplicationViewer(QWidget *parent) :
    QmlApplicationViewer(parent),
    m_screenSizeProvider(new ScreenSizeProvider(this))
{
#if defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
    m_rotationData = new RotationData(this);
    m_deviceInfo = new QSystemDeviceInfo(this);
#ifdef INAPP_BILLING
    m_iapmodel = NULL;
    m_featureProvider = NULL;
    iapLoadInterface();
    QString url(m_featureProvider->requestResourceUrl(QLatin1String("audio_motor_sound")));
    m_audioPlayer = new AudioPlayer(this, url);
#else
    m_audioPlayer = new AudioPlayer(this, QLatin1String(":/sounds/motor2.wav")),
#endif //INAPP_BILLING
    m_audioPlayer->profile(m_deviceInfo->currentProfile());
#endif
}


/*!
  Shows the content of the viewer. This is overwritten method of the base
  class, QmlApplicationViewer.
*/
void MyQmlApplicationViewer::showExpanded()
{
#ifdef Q_WS_MAEMO_6
    setGeometry(m_screenSizeProvider->size());
    showFullScreen();
#else
    QmlApplicationViewer::showExpanded();
#endif
}


/*!
  Connects all the required signals.
*/
void MyQmlApplicationViewer::connectSignals()
{
    QObject *qmlObject = rootObject();
    connect(qmlObject, SIGNAL(speedChanged(qreal)), m_audioPlayer, SLOT(setSpeed(qreal)));
    connect(qmlObject, SIGNAL(stopAudio()), m_audioPlayer, SLOT(stop()));
    connect(qmlObject, SIGNAL(startAudio()), m_audioPlayer, SLOT(start()));
    connect(qmlObject, SIGNAL(splitVKB()), SLOT(enableSplitSreen()));

#if defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
    connect(m_rotationData, SIGNAL(rotationChanged(QVariant)),
            qmlObject, SLOT(updateControls(QVariant)));
    connect(m_rotationData, SIGNAL(tiltedLeft()), qmlObject, SLOT(tiltLeft()));
    connect(m_rotationData, SIGNAL(tiltedRight()), qmlObject, SLOT(tiltRight()));
    connect(m_deviceInfo, SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
            m_audioPlayer, SLOT(profile(QSystemDeviceInfo::Profile)));
#endif

#ifdef INAPP_BILLING
    connect(m_iapmodel, SIGNAL(appPurchaseCompleted(QVariant)), qmlObject, SLOT(appPurchaseCompleted(QVariant)));
#endif
}


/*!
  Launches the game with splash screen.
*/
void MyQmlApplicationViewer::launchWithSplashScreen()
{
    // Expose the screen size provider in order for it to be accessible within
    // the QML code.
    engine()->rootContext()->setContextProperty("screenSizeProvider",
                                                m_screenSizeProvider);

    setMainQmlFile(QLatin1String("qml/mototrialracer/SplashScreen.qml"));
    showExpanded();
    showMainScreen();
}


/*!
  Enables the split screen support for the virtual keyboard on Symbian
  platform.
*/
void MyQmlApplicationViewer::enableSplitSreen()
{
#if defined(Q_OS_SYMBIAN)
    MCoeFepAwareTextEditor *fte =
            CCoeEnv::Static()->AppUi()->InputCapabilities().FepAwareTextEditor();

    // FepAwareTextEditor() returns 0 if no text editor is present
    if (fte)
    {
        qDebug() << "Text editor is present";
        CAknEdwinState *state =
                STATIC_CAST(CAknEdwinState*, fte->Extension1()->State(KNullUid));
        state->SetFlags(state->Flags() | EAknEditorFlagEnablePartialScreen);
    }
    else
        qDebug() << "Text editor is NOT present";
#endif
}


/*!
  Loads the game i.e. loads the main QML file and connects the required
  signals.
*/
void MyQmlApplicationViewer::loadGame()
{
    // Load the main QML file and connect signals.
    setMainQmlFile(QLatin1String("qml/mototrialracer/main.qml"));
    connectSignals();
}

void MyQmlApplicationViewer::showMainScreen()
{
    // when new QML source is set existing object hierarchy is destroyed
    // to avoid panic we need async call to replace QML content
    QMetaObject::invokeMethod(this, "loadGame", Qt::QueuedConnection);
}

#ifdef INAPP_BILLING
void MyQmlApplicationViewer::iapLoadInterface()
{
    if(m_iapmodel)
        return;

    //connecting model to QML
    m_iapmodel = new ProductCatalogModel(this);
    rootContext()->setContextProperty("catalogModel", m_iapmodel);

    ItemstatusImageProvider* iapImageProvider = new ItemstatusImageProvider(*m_iapmodel);
    engine()->addImageProvider("imagestatusprovider", iapImageProvider); //NOTE: it takes ownership of provider

    m_featureProvider = new ResourceDataProvider(*m_iapmodel->dataModel());
    engine()->addImageProvider("productimageprovider", m_featureProvider); //NOTE: it takes ownership of provider
    // for non-Image data interaction between C++ and QML
    rootContext()->setContextProperty("productFeatureProvider", m_featureProvider);
}

void MyQmlApplicationViewer::appPurchaseCompleted(QVariant isUnlocked)
{
    if(!m_featureProvider)
    {
        return;
    }

    if(!isUnlocked.toBool())
    {
        return;
    }

    delete m_audioPlayer;
    QString url(m_featureProvider->requestResourceUrl(QLatin1String("audio_motor_sound")));
    m_audioPlayer = new AudioPlayer(this, url);
    m_audioPlayer->profile(m_deviceInfo->currentProfile());

    QObject *qmlObject = rootObject();
    connect(qmlObject, SIGNAL(speedChanged(qreal)), m_audioPlayer, SLOT(setSpeed(qreal)));
    connect(qmlObject, SIGNAL(stopAudio()), m_audioPlayer, SLOT(stop()));
    connect(qmlObject, SIGNAL(startAudio()), m_audioPlayer, SLOT(start()));

#if defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
    connect(m_deviceInfo, SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
            m_audioPlayer, SLOT(profile(QSystemDeviceInfo::Profile)));
#endif

}

#endif //INAPP_BILLING
